package com.ruoyi.asms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.ams.controller.AmsOwnAddressController;
import com.ruoyi.ams.domain.vo.AddressAssetInfoVo;
import com.ruoyi.asms.domain.AsmsMaintenanceAsset;
import com.ruoyi.asms.domain.AsmsOwnAddressAssetCode;
import com.ruoyi.asms.domain.AsmsOwnMaintenanceDept;
import com.ruoyi.asms.domain.vo.AsmsOwnAddressAssetCodeAddVo;
import com.ruoyi.asms.domain.vo.AsmsOwnAddressAssetCodeEditVo;
import com.ruoyi.asms.domain.vo.AsmsOwnAddressAssetCodeVo;
import com.ruoyi.asms.service.IAsmsMaintenanceAssetService;
import com.ruoyi.asms.service.IAsmsOwnAddressAssetCodeService;
import com.ruoyi.asms.service.IAsmsOwnMaintenanceDeptService;
import com.ruoyi.asms.service.AsmsReusingService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.AmsOwnAddress;
import com.ruoyi.common.core.domain.vo.AddressAssetCodeVo;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.security.service.TokensService;
import com.ruoyi.file.controller.SysFileController;
import com.ruoyi.system.controller.SysDeptController;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 位置码信息Controller
 *
 * @author yfkj
 * @date 2021-10-21
 */
@RestController
@RequestMapping("/asms/AsmsOwnAddressAssetCode")
public class AsmsOwnAddressAssetCodeController extends BaseController {
    @Autowired
    private IAsmsOwnAddressAssetCodeService asmsOwnAddressAssetCodeService;

    @Autowired
    private IAsmsMaintenanceAssetService asmsMaintenanceAssetService;
    @Autowired
    private TokensService tokenService;
    @Autowired
    private AsmsReusingService asmsReusingService;
    @Autowired
    private IAsmsOwnMaintenanceDeptService asmsOwnMaintenanceDeptService;

//    @Autowired
//    private RemoteAssetAddressService remoteAssetAddressService;
//    @Autowired
//    private RemoteDeptService remoteDeptService;
//    @Autowired
//    private RemoteFileService remoteFileService;
    @Autowired
    private AmsOwnAddressController ownAddressController;
    @Autowired
    private SysDeptController deptController;
    @Autowired
    private SysFileController fileController;

    /**
     * 查询位置码信息列表
     */
    //@PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnAddressAssetCode:list")
    @GetMapping("/list")
    @ApiOperation("获取区域地址码列表：可以根据位置报修码、组织部门deptId、区域addressId搜索\n" +
            "注意获取区域下拉搜索条件时需要根据选择的组织部门deptId来动态获取区域下拉列表（调这个接口时传deptId：ams/AmsOwnAddress/treeselect）\n" +
            "如果没有选择组织部门deptId,请默认携带组织部门列表的第一个Id")
    public TableDataInfo list(AsmsOwnAddressAssetCode asmsOwnAddressAssetCode) {
        QueryWrapper<AsmsOwnAddressAssetCode> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(asmsOwnAddressAssetCode.getCode())) {
            wrapper.like(AsmsOwnAddressAssetCode.CODE, asmsOwnAddressAssetCode.getCode());
        }
        if (asmsOwnAddressAssetCode.getDeptId() != null) {
            wrapper.eq(AsmsOwnAddressAssetCode.DEPT_ID, asmsOwnAddressAssetCode.getDeptId());
        }
        if (asmsOwnAddressAssetCode.getAddressId() != null) {
            wrapper.eq(AsmsOwnAddressAssetCode.ADDRESS_ID, asmsOwnAddressAssetCode.getAddressId());
        }
        //管理员查看所有数据、其他人员查看本部门可见的数据
        Set<Long> userCanLookDeptIds = tokenService.getUserMaintenanceDeptIds();
        Set<Long> canLook=new HashSet<>();
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && userCanLookDeptIds != null && userCanLookDeptIds.size() > 0) {
            List<AsmsOwnMaintenanceDept> list = asmsOwnMaintenanceDeptService.list(new QueryWrapper<AsmsOwnMaintenanceDept>().in(AsmsOwnMaintenanceDept.MAINTENANCE_DEPT_ID, userCanLookDeptIds).orderByAsc(AsmsOwnMaintenanceDept.OWN_DEPT_ID).select(AsmsOwnMaintenanceDept.OWN_DEPT_ID));
            if(list.size()>0){
                list.forEach(item->canLook.add(item.getOwnDeptId()));
            }
        }
        Set<Long> userOwnDeptIds = tokenService.getUserOwnDeptIds();
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && userOwnDeptIds != null && userOwnDeptIds.size() > 0) {
            canLook.addAll(userOwnDeptIds);
        }
        wrapper.in(canLook.size()>0, AsmsOwnAddressAssetCode.DEPT_ID, canLook);
        wrapper.orderByDesc(AsmsOwnAddressAssetCode.CREATE_TIME);
        startPage();
        List<AsmsOwnAddressAssetCode> list = asmsOwnAddressAssetCodeService.list(wrapper);
        List<AsmsOwnAddressAssetCodeVo> vos = new ArrayList<>();

        //构造资产区域map,提高查询速度
        R<List<AmsOwnAddress>> addressList = ownAddressController.getAddressList();
        if (addressList.getCode() == R.FAIL) {
            throw new ServiceException(addressList.getMsg());
        }
        HashMap<Long, AmsOwnAddress> addressHashMap = new HashMap<>();
        for (AmsOwnAddress ownAddress : addressList.getData()) {
            addressHashMap.put(ownAddress.getAddressId(), ownAddress);
        }

        //构造部门map,提高查询速度
        R<List<SysDept>> deptList = deptController.getDeptList();
        if (deptList.getCode() == R.FAIL) {
            throw new ServiceException(deptList.getMsg());
        }
        HashMap<Long, SysDept> deptHashMap = new HashMap<>();
        for (SysDept sysDept : deptList.getData()) {
            deptHashMap.put(sysDept.getDeptId(), sysDept);
        }

        for (AsmsOwnAddressAssetCode codeInfo : list) {
            AsmsOwnAddressAssetCodeVo vo = new AsmsOwnAddressAssetCodeVo();
            BeanUtils.copyProperties(codeInfo, vo);
            AmsOwnAddress ownAddress = addressHashMap.get(codeInfo.getAddressId());
            if (ownAddress != null) {
                BeanUtils.copyProperties(ownAddress, vo);
            }

            SysDept sysDept = deptHashMap.get(codeInfo.getDeptId());
            if (sysDept != null) {
                BeanUtils.copyProperties(sysDept, vo);
            }
            vo.setCreateBy(codeInfo.getCreateBy());
            vo.setCreateTime(codeInfo.getCreateTime());
            vos.add(vo);
        }
        return getDataTable(vos);
    }

    /**
     * 导出位置码信息列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnAddressAssetCode:export")
    @Log(title = "位置码信息", businessType = BusinessType.EXPORT)
    @PostMapping(value="/export", produces = "application/octet-stream")
    public void export(HttpServletResponse response, AsmsOwnAddressAssetCode asmsOwnAddressAssetCode) throws IOException {
        List<AsmsOwnAddressAssetCode> list = asmsOwnAddressAssetCodeService.selectAsmsOwnAddressAssetCodeList(asmsOwnAddressAssetCode);
        ExcelUtil<AsmsOwnAddressAssetCode> util = new ExcelUtil<AsmsOwnAddressAssetCode>(AsmsOwnAddressAssetCode.class);
        util.exportExcel(response, list, "位置码信息数据");
    }

    /**
     * 获取位置码信息详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnAddressAssetCode:query")
    @GetMapping(value = "/{addressCodeId}")
    public AjaxResult getInfo(@PathVariable("addressCodeId") Long addressCodeId) {
        return AjaxResult.success(asmsOwnAddressAssetCodeService.selectAsmsOwnAddressAssetCodeByAddressCodeId(addressCodeId));
    }

    /**
     * 新增位置码信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnAddressAssetCode:add")
    @Log(title = "位置码信息", businessType = BusinessType.INSERT)
    @PostMapping("/addAsmsOwnAddressAssetCode")
    @ApiOperation("新增区域位置码信息")
    public AjaxResult add(@RequestBody AsmsOwnAddressAssetCodeAddVo asmsOwnAddressAssetCodeAddVo) {
        AsmsOwnAddressAssetCode asmsOwnAddressAssetCode = new AsmsOwnAddressAssetCode();
        BeanUtils.copyProperties(asmsOwnAddressAssetCodeAddVo, asmsOwnAddressAssetCode);
        asmsOwnAddressAssetCode.setCreateBy(SecurityUtils.getUsername());
        asmsOwnAddressAssetCode.setCreateTime(System.currentTimeMillis());
        return toAjax(asmsOwnAddressAssetCodeService.save(asmsOwnAddressAssetCode));
    }

    /**
     * 修改位置码信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsOwnAddressAssetCode:edit")
    @Log(title = "位置码信息", businessType = BusinessType.UPDATE)
    @PutMapping("/editAsmsOwnAddressAssetCode")
    @ApiOperation("修改区域位置码信息")
    public AjaxResult edit(@RequestBody AsmsOwnAddressAssetCodeEditVo asmsOwnAddressAssetCodeEditVo) {
        AsmsOwnAddressAssetCode asmsOwnAddressAssetCode = new AsmsOwnAddressAssetCode();
        BeanUtils.copyProperties(asmsOwnAddressAssetCodeEditVo, asmsOwnAddressAssetCode);
        asmsOwnAddressAssetCode.setUpdateBy(SecurityUtils.getUsername());
        asmsOwnAddressAssetCode.setUpdateTime(System.currentTimeMillis());
        return toAjax(asmsOwnAddressAssetCodeService.updateById(asmsOwnAddressAssetCode));
    }

    /**
     * 删除位置码信息
     */
    @PreAuthorize
    @Log(title = "位置码信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{addressCodeIds}")
    public AjaxResult remove(@PathVariable Long[] addressCodeIds) {
        return toAjax(asmsOwnAddressAssetCodeService.deleteAsmsOwnAddressAssetCodeByAddressCodeIds(addressCodeIds));
    }

    @PreAuthorize
    @GetMapping("/scanCodeInfo")
    @ApiOperation("扫码报修")
    public AjaxResult scanCodeInfo(@ApiParam(value = "报修码", name = "code", required = true)
                                       @RequestParam("code") String code) {
        //查询二维码
        AsmsOwnAddressAssetCode codeInfo = asmsOwnAddressAssetCodeService
                .getOne(new QueryWrapper<AsmsOwnAddressAssetCode>()
                        .select(AsmsOwnAddressAssetCode.DEPT_ID, AsmsOwnAddressAssetCode.ADDRESS_ID)
                        .eq(AsmsOwnAddressAssetCode.CODE, code), false);
        if (codeInfo == null) return error("二维码不存在！");

        //根据二维码查询资产与位置信息
        R<AddressAssetInfoVo> rAddressAssetInfoVo = ownAddressController
                .getAddressDeptAssetInfo(codeInfo.getAddressId(), codeInfo.getDeptId());

        if (R.FAIL == rAddressAssetInfoVo.getCode()) {
            throw new ServiceException(rAddressAssetInfoVo.getMsg());
        }
        return AjaxResult.success(rAddressAssetInfoVo.getData());
    }

    @PostMapping("/insertAddressCodeAssetId")
    public R insertAddressCodeAssetId(@RequestBody AddressAssetCodeVo vo) {
        AsmsOwnAddressAssetCode asmsOwnAddressAssetCode = new AsmsOwnAddressAssetCode();
        asmsOwnAddressAssetCode.setAddressId(vo.getAddressId());
        asmsOwnAddressAssetCode.setAssetId(vo.getAssetId());
        asmsOwnAddressAssetCode.setCode(vo.getCode());
        asmsOwnAddressAssetCode.setDeptId(vo.getDeptId());
        List<AsmsOwnAddressAssetCode> codes = asmsOwnAddressAssetCodeService.
                list(new QueryWrapper<AsmsOwnAddressAssetCode>().eq("code", vo.getCode()));
        if (codes != null && codes.size() > 0) {
            asmsOwnAddressAssetCodeService.remove(new QueryWrapper<AsmsOwnAddressAssetCode>().eq("code", vo.getCode()));
        }
        AsmsMaintenanceAsset asmsMaintenanceAsset = new AsmsMaintenanceAsset();
        asmsMaintenanceAsset.setAssetId(vo.getAssetId());
        asmsMaintenanceAsset.setMaintenanceDeptId(vo.getDeptId());
        asmsMaintenanceAsset.setStartUseTime(System.currentTimeMillis());
        asmsMaintenanceAsset.setEndUseTime(System.currentTimeMillis()+100000000000L);
        asmsMaintenanceAsset.setIsDelete(1);

        asmsMaintenanceAssetService.save(asmsMaintenanceAsset);
        asmsOwnAddressAssetCodeService.save(asmsOwnAddressAssetCode);
        return R.ok();
    }

    @GetMapping("/getAddressCodeInfoByCode/{code}")
    public R<Long> getAddressCodeInfoByCode(@PathVariable("code") String code) {
        List<AsmsOwnAddressAssetCode> infos = asmsOwnAddressAssetCodeService.list(new QueryWrapper<AsmsOwnAddressAssetCode>().eq("code", code));

        if (infos != null)
        {
            if(infos.size() > 0){
                return  R.ok(infos.get(0).getAssetId());
            }else {
                return  R.ok(-1l);
            }
        }

        return  R.fail("售后维护错误");
    }


}
